﻿using System;
using Runtime.Common.Object;
using Runtime.CoreAttribute;
using Runtime.ObjectBehaviour.Interface;
using Runtime.Common.Interface;
using Runtime.Common.Interface.GameWorld.Core.Interface;
using Runtime.Data.Interface;
using UnityEngine;

namespace Runtime.DesignPattern
{
    [IgnoreStaticObjectRestore]
    public class SingletonOfObject<T> : MonoBehaviour, IGameSingleton, IInit, IReset, IIsDestroy
        where T : Component, IGameSingleton
    {
        private static Lazy<T> _inst = new(new GameObject(typeof(T).Name).AddComponent<T>);

        protected SingletonOfObject()
        {
        }

        public static T Inst => _inst.Value;
        public IGuidObject Id { get; } = new GuidObject();

        public void Destroy()
        {
            _inst = default;
        }

        public virtual void Init(IFunctionParameter data = null)
        {
            SingletonRegister.Register(_inst.Value);
        }

        public virtual bool IsDestroy { get; } = true;

        public void Reset()
        {
            if (_inst.Value)
            {
                Destroy(_inst.Value);
                _inst = new Lazy<T>(new GameObject(typeof(T).Name).AddComponent<T>);
            }
        }

        public virtual void Init()
        {
        }
    }
}